/*
 * @FileName: bsp_uart.c
 * @Author: GreyQiu qiushaogui@aikosolar.com
 * @Date: 2023-08-21 10:50:15
 * @LastEditors: GreyQiu qiushaogui@aikosolar.com
 * @LastEditTime: 2023-09-20 14:35:30
 * @Description: 
 * 
 * Copyright (c) 2023, All Rights Reserved. 
 */

#include "bsp_can.h"
#include "bsp.h"
#include "bms_can.h"

#define TX_MSG_OBJ_ID 1
#define RX_MSG_OBJ_ID 2

static uint16_t can_tx_buffer[8];
uint16_t can_rx_buffer[8];
static uint32_t can_msg_id;
static CAN_MsgFrameType can_msg_type;

__interrupt void canaISR(void)
{
    uint32_t status;

    status = CAN_getInterruptCause(CANA_BASE);

    if(status == CAN_INT_INT0ID_STATUS)
    {
        status = CAN_getStatus(CANA_BASE);


        if(((status  & ~(CAN_STATUS_RXOK)) != CAN_STATUS_LEC_MSK) &&
           ((status  & ~(CAN_STATUS_RXOK)) != CAN_STATUS_LEC_NONE))
        {

        }
    }
    else if(status == RX_MSG_OBJ_ID)
    {
        CAN_readMessageWithID(CANA_BASE, RX_MSG_OBJ_ID, &can_msg_type, &can_msg_id, can_rx_buffer);
        CAN_clearInterruptStatus(CANA_BASE, RX_MSG_OBJ_ID);
        bms_handle(can_msg_id, can_rx_buffer, 8);
    }
    else
    {

    }

    CAN_clearGlobalInterruptStatus(CANA_BASE, CAN_GLOBAL_INT_CANINT0);
    Interrupt_clearACKGroup(INTERRUPT_ACK_GROUP9);
}

void bsp_can_init(void)
{
    GPIO_setPinConfig(GPIO_CFG_CANRXA);
    GPIO_setPinConfig(GPIO_CFG_CANTXA);

    CAN_initModule(CANA_BASE);

    CAN_setBitRate(CANA_BASE, DEVICE_SYSCLK_FREQ, 500000, 20);

    CAN_setupMessageObject(CANA_BASE, RX_MSG_OBJ_ID, 0x300,
                           CAN_MSG_FRAME_STD, CAN_MSG_OBJ_TYPE_RX, 0x300,
                           CAN_MSG_OBJ_RX_INT_ENABLE | CAN_MSG_OBJ_USE_ID_FILTER, 8);

    CAN_enableInterrupt(CANA_BASE, CAN_INT_IE0 | CAN_INT_ERROR | CAN_INT_STATUS);

    Interrupt_register(INT_CANA0,&canaISR);

    //
    // Enable the CAN-A interrupt signal
    //
    Interrupt_enable(INT_CANA0);
    CAN_enableGlobalInterrupt(CANA_BASE, CAN_GLOBAL_INT_CANINT0);
    CAN_startModule(CANA_BASE);
}

void bsp_can_send(uint8_t * buffer, uint32_t len)
{

}

void bsp_can_callback_register(can_rxc_calllback cb)
{

}
